from flask import Blueprint, render_template, current_app, redirect, url_for, flash
from app.models import Article
from app.scraper import scrape_by_category

bp = Blueprint('main', __name__)

@bp.route('/')
def index():
    articles = Article.query.order_by(Article.published_at.desc()).all()
    # 将分类信息传递给模板
    categories = current_app.config['CATEGORIES']
    return render_template('index.html', articles=articles, categories=categories)

@bp.route('/category/<category_name>')
def show_category(category_name):
    categories = current_app.config['CATEGORIES']
    if category_name not in categories:
        flash('无效的分类!', 'danger')
        return redirect(url_for('main.index'))
    
    articles = Article.query.filter_by(category=category_name).order_by(Article.published_at.desc()).all()
    return render_template('index.html', articles=articles, categories=categories, current_category=category_name)

@bp.route('/scrape/<category_name>')
def scrape_now(category_name):
    categories = current_app.config['CATEGORIES']
    if category_name not in categories:
        flash('无效的分类!', 'danger')
        return redirect(url_for('main.index'))
    
    rss_url = categories[category_name]
    scrape_by_category(category_name, rss_url)
    flash(f'分类 [{category_name}] 已成功抓取！', 'success')
    return redirect(url_for('main.index'))
